from django.shortcuts import render
from django.views import View
from apps.contents.models import GoodsCategory
from apps.goods.models import SKU
from django import http
from django.core.paginator import Paginator, EmptyPage
from apps.goods.utils import get_breadcrumb
from haystack.views import SearchView


# Create your views here.

class ListView(View):
    """商品列表"""

    def get(self, request, category_id):
        # 获取参数
        page = request.GET.get('page')
        page_size = request.GET.get('page_size')
        ordering = request.GET.get('ordering')

        # 校验参数
        # 传过来的是三级分类的商品分类id 我们要校验一下存不存在
        try:
            category = GoodsCategory.objects.get(id=category_id)
        except GoodsCategory.DoesNotExist:
            return http.JsonResponse({'code': 400, 'errmsg': '参数category_id不存在'})

        try:
            # 获取三级分类对应的数据，上架的，进行排序
            skus = SKU.objects.filter(category=category, is_launched=True).order_by(ordering)
        except SKU.DoesNotExist:
            return http.JsonResponse({'code': 400, 'errmsg': '获取SKU数据出错'})

        # 分页显示,要显示的查询集，一页显示几个
        paginator = Paginator(skus, page_size)

        try:
            # 获取当前页面的数据
            page_skus = paginator.page(page)
        except EmptyPage:
            return http.JsonResponse({'code': 400, 'errmsg': '获取当前页面的数据错误'})

        # 总页数
        total_pages = paginator.num_pages

        list = []
        for sku in page_skus:
            list.append({
                "id": sku.id,
                "default_image_url": sku.default_image.url,
                "name": sku.name,
                "price": sku.price
            })

        # 面包屑导航数据
        breadcrumb = get_breadcrumb(category)

        return http.JsonResponse({
            'code': 0,
            'errmsg': 'OK',
            'breadcrumb': breadcrumb,  # 面包屑导航
            'list': list,  # 排序后的分页数据，不能是模型数据，因为JsonResponse不识别
            'count': total_pages  # 分页后的总页数
        })


class HotGoodsView(View):
    """热销排行"""

    def get(self, request, category_id):
        # 通过商品分类id 查询前两名销售最大的，显示的商品
        try:
            category = GoodsCategory.objects.get(id=category_id)
        except GoodsCategory.DoesNotExist:
            return http.JsonResponse({'code': 400, 'errmsg': '参数category_id不存在'})

        skus = SKU.objects.filter(category=category, is_launched=True).order_by('-sales')[:2]

        hot_skus_list = []
        for sku in skus:
            hot_skus_list.append({
                "id": sku.id,
                "default_image_url": sku.default_image.url,
                "name": sku.name,
                "price": sku.price
            })

        return http.JsonResponse({
            "code": "0",
            "errmsg": "OK",
            "hot_skus": hot_skus_list
        })


class MySearchView(SearchView):
    """重新 haystack 里的 SearchView 里的 create_response
    方法，这个方法返回的是搜索到内容返回HTML文件,重写返回我们需要的json数据"""

    def create_response(self):
        # 查询索引数据到的返回数据
        context = self.get_context()

        data_list = []
        # 利用断点查看context的结果再来写后面怎么找到查询到的SKU数据
        for result in context['page'].object_list:
            data_list.append({
                'id': result.object.id,
                'name': result.object.name,
                'price': result.object.price,
                'default_image_url': result.object.default_image.url,
                'searchkey': context.get('query'),
                'page_size': context['page'].paginator.num_pages,
                'count': context['page'].paginator.count
            })

        # 为了允许非dict对象被序列化，将' '安全参数设置为False
        return http.JsonResponse(data_list, safe=False)
